// pages/turntable/turntable.js
const seversField = getApp().data;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    balance: '',//剩余金额
    coin:'',
    isIpx:false,
    userInfo:'',
    animationData: '',
    currentRotateDeg: 0,
    baseTimer: 4000,
    baseRound: 15,
    isRotate: false,
    token: '',
    modalControl:false,
    showPrizeImgUrl:'',
    modalTitle:'',
    prompt: '您的金币不足了哦~',
    rotateFields: {
      '50coin': 360,
      '100coin': 270,
      '200coin': 180,
      '500coin': 90,
      '0game_code': 315,
      '5telephone': 225,
      '10telephone': 45,
      'pp_vip': 135,
    },
    gameName:'',
    codeNum:'',
    showGameName:false,
    

    textM: 0,
    textN: '',
    textW: 0,
    textL: 50, 
  },
  submitform(e) {
    let form_id = e.detail.formId;
    if (this.data.isRotate) return;
    if (this.data.balance < 200) {
      wx.showToast({
        title: this.data.prompt,
        mask: true,
        icon:'none'
      })
      return;
    }
    wx.request({
      url: seversField.commonUrl + seversField.dir + '/WheelSurf',
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + this.data.token,
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: res => {
        if (res.data.code == 0) {
          wx.request({
            url: app.data.commonUrl + app.data.taskUrl,
            header: {
              "Content-Type": "application/x-www-form-urlencoded",
              "Authorization": 'Bearer ' + this.data.token,
            },
            method: 'GET',
            data: {
              task_name: 'lottery',
              appflag: app.data.appflag,
            },
            success: res => {
              if (app.data.current_num<=4){
                app.data.showResiveFlag = true;
                app.data.showResiveTip = '完成抽奖任务';
                app.data.showResiveIcon = 100;
              }                          
            }
          })
          const field = res.data.result.num + res.data.result.type,
                res_type = res.data.result.type;
          this.animationStart(this.data.rotateFields[field]);
          app.data.countGlobal.whellSurfCount('click', `${res.data.result.type}_${res.data.result.num}`);//统计
          if (res_type == 'telephone' || res_type == 'pp_vip' || res_type == 'game_code' ){
            if (res_type == 'game_code'){
              this.setData({
                gameName: res.data.result.code[0],
                codeNum: res.data.result.code[1],
                showGameName:true
              })
            }
            this.sendTplMsg(res.data.result, form_id)
          }
          this.setData({
            showPrizeImgUrl:`/resourse/${field}.png`,
            modalTitle:res.data.result.title,
            coin:res.data.result.coin,
          })
        }
      }
    })
  },
  sendTplMsg(res,id) {
    let keyword=[];
    if (res.code.length>2){
      keyword = [res.code[1], res.code[2], res.code[0]]
    }else{
      keyword = [res.code[0], res.code[1],'赶快去使用吧']
    }
    wx.request({
      method: 'POST',
      url: app.data.commonUrl + 'Server/Wechat/templateMessage',
      header: {
        authorization: 'bearer ' + this.data.token,
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        appflag: app.data.appflag,
        keyword: keyword,
        form_id: id,
        tpl: 'giftCode',
        page: 'pages/index/index',
        emphasis:'keyword1.DATA'
      },
      success: function (result) {
        console.log(res);
      }
    });

  },
  //转盘旋转结束
  rotateEnd() {
    this.setData({
      balance:this.data.coin,
      isRotate: false,
      modalControl:true,
    })
  },
  closeModal(){ 
    this.setData({
      modalControl: false
    })
  },
  goBack(){
    // wx.navigateBack();
    wx.switchTab({
      url: '../my/my',

    })
  },
  //点击开始旋转
  animationStart(deg) {
    const animation = wx.createAnimation({
      duration: this.data.baseTimer + this.randomTimer([1000, 2000]),
      timingFunction: 'ease-in-out',
    })
    this.animation = animation;
    animation.rotate(this.data.baseRound * 360 + this.data.currentRotateDeg + deg).step();
    this.setData({
      isRotate: true,
      animationData: animation.export(),
      currentRotateDeg: this.data.currentRotateDeg + this.data.baseRound * 360
    })
  },
  randomTimer(timecase) {
    const max = Math.max(...timecase)
      , min = Math.min(...timecase)
    return Math.ceil(Math.random() * (max - min));
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const token = wx.getStorageSync('sessionid_pro');
    const userInfo = wx.getStorageSync('userInfo');
    const isIpx = seversField.isIPhoneX;
    this.setData({
      token, userInfo, isIpx
    });
    this.requestControler(
      seversField.commonUrl + seversField.dir + '/WheelSurf',
      'GET', res => {
        this.setData({
          balance: res.data.result.coin,
          textN: res.data.result.scroll_prompt
        })
        let that = this,
            textM = 20,
            phoneWidth = wx.getSystemInfoSync().windowWidth,//获取屏幕宽度的封装方法
            textW = parseInt(Number(that.data.textN.length) * 8);//文字宽度=文字长度+字体大小
        that.setData({ textW: textW, textL: phoneWidth });
        if (phoneWidth > textW) {
          let centerL = Number(phoneWidth / 2) - (Number(textW) / 2);
          that.setData({ textL: centerL });
        } else {
          clearInterval(textTime);
          var textTime = setInterval(function () {
            let textL = that.data.textL;
            if (textL < -(textW - 20)) {
              that.setData({ textL: phoneWidth })
              return
            }
            textL -= 2;
            that.setData({ textL: textL })
          }, 30)
        }

      }
    );  

  },
  onHide(){
    // textTime
  },
  requestControler(url, method, successCallback ) {
    const conf = {};
    conf.url = url;
    conf.method = method;
    conf.header = method === 'POST' ?
      {
        "Authorization": 'Bearer ' + this.data.token,
        "Content-Type": "application/x-www-form-urlencoded"
      } : 
      {
        "Authorization": 'Bearer ' + this.data.token,
      }
    conf.success = res => {
      successCallback(res);
    }
    wx.request(conf);
  },
  onShow(){
    app.data.countGlobal.setEnv(app.data.optGlobal);
    app.data.countGlobal.setOpenid(wx.getStorageSync('uid'));
    app.data.countGlobal.whellSurfCount('enter');//统计

  },
  copyText(e){
    let copy_data = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: copy_data,
      success: res => {
        wx.showToast({
          title: '复制成功~',
          icon: 'none',
          duration: 1500,
          mask: true,
          isDone: false
        })
        this.closeModal()
      }
    })
  }
})